package com.sharing.library.controller;

import com.sharing.library.entity.Book;
import com.sharing.library.entity.User;
import com.sharing.library.repository.BookRepository;
import com.sharing.library.repository.UserRepository;
import com.sharing.library.repository.dto.BookCondition;
import com.sharing.library.repository.spec.BookSpec;
import com.zhx.framework.util.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhanghaixuan
 * @create 2018/3/17-下午2:03
 **/
@RestController
@RequestMapping("/book")
@Api(description="书管理")
public class BookController {
    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private UserRepository userRepository;

    //获取列表
    //列表
    @PostMapping("/list")
    @ApiOperation(value="获取书的列表", notes="获取书的列表")
    public Result list (BookCondition condition, Pageable pageable){

        Page<Book> books = bookRepository.findAll(new BookSpec(condition), pageable);

        return Result.OK("",books);
    }

    //详情
    @PostMapping("/detail")
    @ApiOperation(value="详情", notes="详情")
    public Result detail(@RequestParam Long id){
        Book one = bookRepository.findOne(id);
        User one1 = userRepository.findOne(Long.parseLong(one.getSubmitUserId()));
        one.setSubmitUserName(one1.getUsername());
        bookRepository.save(one);
        return Result.OK("",one);
    }


    //更新状态
    @PostMapping("/update")
    @ApiOperation(value="修改状态", notes="修改状态")
    public Result update(@RequestParam Long id,@RequestParam String state){
        Book one = bookRepository.findOne(id);
        one.setState(state);
        return Result.OK("",bookRepository.save(one));
    }

    //更新书籍
    @PostMapping("/save")
    @ApiOperation(value="更新书籍", notes="更新书籍")
    public Result update(@RequestBody Book book){
        Book one = bookRepository.save(book);
        return Result.OK("",one);
    }

}
